package com.rclabs.preloaders.preloader1
{
	import mx.preloaders.DownloadProgressBar;
	import flash.display.Sprite;
	import flash.events.ProgressEvent;
	import flash.events.Event;
	import mx.events.FlexEvent;
	import mx.managers.SystemManager;
	import mx.managers.BrowserManager;
	import flash.utils.Timer;
	import flash.events.TimerEvent;
	
	public class Preloader extends DownloadProgressBar
	{
		public var progressBar: ProgressBar;
		private var timer: Timer;
		
		public function Preloader(): void{
			super();
			var browser: BrowserManager;
			progressBar = new ProgressBar;            
			this.addChild(progressBar);
			progressBar.addEventListener(ProgressBar.FADE_OUT_COMPLETE,fadeOutCompleteHandler, false, 0, true);
			timer = new Timer(1);
			timer.addEventListener(TimerEvent.TIMER, timerEventHandler, false, 0, true);
			timer.start();
		}
		override public function set preloader(value:Sprite):void{
			value.addEventListener(ProgressEvent.PROGRESS, progressEventHandler, false, 0, true);
			value.addEventListener(Event.COMPLETE, completeEventHandler, false, 0, true);
			value.addEventListener(FlexEvent.INIT_PROGRESS, initProgressEventHandler, false, 0, true);
			value.addEventListener(FlexEvent.INIT_COMPLETE, initCompleteEventHandler, false, 0, true);            
		}        
		private function progressEventHandler(event: ProgressEvent): void{
			var progress: Number = event.bytesLoaded / event.bytesTotal;
			
			if (progressBar){
				progressBar.progress = progress;
			}
			
		}
		private function timerEventHandler(event: TimerEvent): void{
			progressBar.visible = (progressBar.width > 0);
			if(progressBar) {
				progressBar.x = (this.stage.stageWidth - progressBar.width) / 2;
				progressBar.y = (this.stage.stageHeight - progressBar.height) / 4;
			}
		}
		
		private function completeEventHandler(event: Event): void{
			var i: int = 0;
		}
		private function initProgressEventHandler(event: FlexEvent): void{
			var i: int = 0;
		}
		private function initCompleteEventHandler(event: FlexEvent): void{
			progressBar.progress = 1;
			progressBar.ready = true;
		}
		
		private function fadeOutCompleteHandler(event: Event): void{
			timer.stop();
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
}